import { pointsWithinPolygon } from '@turf/turf';
import type PaintBoard from '..';
import { getPolygon, type Paint, point2Feature } from '../utils';
import Shape from './base';

class Select extends Shape {
  private _prevPosition: GeoJSON.Position | undefined = undefined;

  DrawingStart(e: mapboxgl.MapMouseEvent, pb: PaintBoard): Paint | undefined {
    this.enter();
    this._prevPosition = [e.lngLat.lng, e.lngLat.lat];
    const ptnFeat = point2Feature([e.lngLat.lng, e.lngLat.lat]);
    const find = pb.paints.find((p) => {
      const poly = getPolygon(p);
      const pointsWithin = poly ? pointsWithinPolygon(ptnFeat, poly) : null;
      return pointsWithin !== null && pointsWithin?.features?.length > 0;
    });
    this.paint = find || undefined;
    return this.paint;
  }
  Drawing(e: mapboxgl.MapMouseEvent): Paint | undefined {
    if (this.paint && this._prevPosition) {
      const cur = [e.lngLat.lng, e.lngLat.lat];
      const delta = cur.map((c, i) =>
        this._prevPosition ? c - this._prevPosition[i] : 0,
      );
      this.paint.coordinates.forEach((coord) => {
        coord[0] += delta[0];
        coord[1] += delta[1];
      });
      this._prevPosition = cur;
      const poly = getPolygon(this.paint);
      poly && this.draw2Map(poly.geometry.coordinates as GeoJSON.Position[][]);
    }
    return this.paint;
  }
  DrawingEnd(_e: mapboxgl.MapMouseEvent): Paint | undefined {
    this.exit();
    return this.paint;
  }

  draw2Map(positions: GeoJSON.Position[][]) {
    // 绘制到地图
    const source = this.map?.getSource(this.sourceId) as mapboxgl.GeoJSONSource;
    source?.setData?.({
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: positions[0],
      },
      properties: {},
    });
  }
}

export default Select;
